package com.xlf.service.ai.common;
import com.xlf.common.core.util.StringUtils;
import com.xlf.service.ai.pojo.dto.*;
import com.xlf.service.ai.utils.JacksonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 类型转换工具类
 *
 */
public class ConvertUtils {


    public static ErnieRequest.ErnieRequestBuilder toErnieRequest(ChatErnieRequest chatRequest,
                                                                  List<Message> messagesHistory) {
        return ErnieRequest.builder()
                .userId(chatRequest.getUserId())
                .messages(messagesHistory)
                .temperature(chatRequest.getTemperature())
                .topP(chatRequest.getTopP())
                .penaltyScore(chatRequest.getPenaltyScore())
                .functions(chatRequest.getFunctions())
                .system(chatRequest.getSystem())
                .stop(chatRequest.getStop())
                .disableSearch(chatRequest.getDisableSearch())
                .enableCitation(chatRequest.getEnableCitation());
    }


    public static BaseRequest.BaseRequestBuilder toBaseRequest(ChatBaseRequest chatRequest,
                                                               List<Message> messagesHistory) {

        return BaseRequest.builder()
                .messages(messagesHistory)
                .userId(chatRequest.getUserId());
    }


    public static <T extends ChatBaseRequest> String buildTargetRequestBody(List<Message> messagesHistory,
                                                                        boolean stream,
                                                                        T request) {

        if(StringUtils.isEmpty(messagesHistory))
            messagesHistory = new ArrayList<>();

        Message message = MessageUtils.buildUserMessage(request.getContent());
        messagesHistory.add(message);

        Object targetRequest = null;
        if (request.getClass() == ChatBaseRequest.class) {
            BaseRequest.BaseRequestBuilder requestBuilder = toBaseRequest(request,messagesHistory).stream(stream);
            targetRequest = requestBuilder.build();
        } else if (request.getClass() == ChatErnieRequest.class) {
            ErnieRequest.ErnieRequestBuilder requestBuilder = ConvertUtils.toErnieRequest((ChatErnieRequest) request,messagesHistory).stream(stream);
            targetRequest = requestBuilder.build();
        }
        return JacksonUtils.toJson(targetRequest);
    }

}
